import { createAction } from 'redux-actions'
import { delJson, check, body, getJson, postJson, parseJSON, checkStatus, data } from './util'
import util from '../util'

const initInfo = {
  avatarUrl: "noAvatarUrl",
  createdTime: null,
  emailAddress: null,
  enrollDate: null,
  fullName: "",
  hasReportee: false,
  isUserDeletable: null,
  jobTitleName: null,
  mobilePhone: null,
  orgId: null,
  profileTemplateId: null,
  projectTeamVOs: null,
  reporterFullName: null,
  roleNameList: null,
  teamAdmin: false,
  teamVO: null,
  userEmploymentVO:null,
  userId: null,
  userProfileId: null
};

export
const fetchFeed = createAction('fetch feed', feedId =>
  fetch(`/feeds/${feedId}`, getJson)
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
    .then(data)
)

export
const fetchFeeds = createAction('fetch feeds', (arg, cb) =>
  fetch(`/feeds?${util.body(arg)}`, getJson)
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
    .then(res => {
      cb && cb()
      return res.data
    })
)

export 
const fetchFeedComments = createAction('fetch feedComments', (feedId, arg, cb) =>
  fetch(`/feeds/${feedId}/comments?${util.body(arg)}`, getJson)
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
    .then(res => {
      cb && cb()
      return {
        data: res.data,
        feedId
      }
    })
)

export 
const refreshFeedComments = createAction('refresh feedComments', (feedId, arg) =>
  fetch(`/feeds/${feedId}/comments?${util.body(arg)}`, getJson)
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
    .then(res => ({
      feedId,
      data: res.data
    }))
)

export
const fetchFeedUps = createAction('fetch feedUps', feedId =>
  fetch(`/feeds/${feedId}/thumbupusers`, getJson)
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
    .then(res => {
      return {
        data: res.data,
        feedId
      }
    })
)

export 
const fetchFeedImage = createAction('fetch feed image', ({ feedId, uuid, index/*, size*/ }) =>
	fetch(`/feeds/${feedId}/images/${uuid}`, getJson)
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
		.then(res => ({
      ...res.data,
      feedId,
      index
    }))
)

export
const addFeed = createAction('add feed', (feed, cb) =>
	fetch('/feeds', {
		...postJson, 
		...body({
			...feed,
			images: feed.images.map(img => img.uuid),
			atUsers: feed.atUsers.map(user => ({idValue: user.userId}))
		})
	})
	.then(checkStatus)
	.then(parseJSON)
	.then(check)
	.then(res => {
		cb()
		return {
			...feed,
			feedId: res.data.idValue,
			createdTime: new Date().getTime()
		}
	})
)

// 添加评论
export const addComment = createAction('add comment', (feedId, data, cb) => 
	fetch(`/feeds/${feedId}/comments`, {
		...postJson,
		...body({
      atUsers: data.atUsers.map(usr => ({idValue: usr.userId})),
      content: data.content
		})
  })
  .then(checkStatus)
  .then(parseJSON)
	.then(check)
  .then(res => {
    cb && cb()
    return {
      feedId,
      pageSize: data.pageSize,
      data: {
        ...data,
        commentId: res.data.idValue,
        isDeletable: 1
      }
    }
  })
)

export 
const resetNewsFeed = createAction('reset newsFeed')

// 头部目标/结果搜索
export const fetchSearchList = createAction('fetch at list', (keyword, cb) => {
  let arg = {
    keyword: keyword
  };
  function searchObjecive(){
    return fetch(`/okrs/objectives/search?${util.body(arg)}`, getJson)
    .then(checkStatus)
    .then(parseJSON)
    .then(check)
  }
  function searchKeyResult(){
    return fetch(`/okrs/key-results/search?${util.body(arg)}`, getJson)
    .then(checkStatus)
    .then(parseJSON)
    .then(check)
  }
  return (
    Promise.all([searchObjecive(), searchKeyResult()]).then(res => {
      let arr1 = res[0].data, arr2 = res[1].data;
      let result = arr1.concat(arr2),
          resultLen = arr1.length + arr2.length;
      let d = [];
      for(let index = 0; index < resultLen; index++){
        d.push({ ...initInfo });
        d[index].fullName = result[index].content;
        d[index]["objectiveId"] = result[index].objectiveId;
      }
      return {
        data: d,
        keyword: keyword
      }
    })
  )
})

// @/搜索同事列表
export const fetchAtList = createAction('fetch at list', (arg, type, cb) => {
  if (typeof arg === 'string') {
    arg = {
      keyword: arg
    }
  }
  return (
    fetch(`/usernames/search?${util.body(arg)}`, getJson)
      .then(checkStatus)
      .then(parseJSON)
      .then(check)
      .then(res => {
        cb && cb(res.data.UserProfiles)
        let allBody = [], list = [];
        if(type){ // 传值认为有@功能
          let dept = [];
          allBody = [{...initInfo}];
          allBody[0].fullName = "所有人"; // 添加@所有人
          res.data.teamListDTO && res.data.teamListDTO.teamDTOList.forEach((item, index) => { // 添加@部门
            dept.push({ ...initInfo });
            dept[index].fullName = item.teamName;
          });
          list = list.concat(allBody, dept);
        }
        list = list.concat(res.data.UserProfiles);
        return {
          data: list,
          keyword: arg.keyword
        }
      })
  )
})

// clear@列表
export const clearAtList = createAction('clear at list')

// 请求feed图片上传地址
export const requestFeedImagesUploadUrl = createAction('_', cb => 
	fetch('/feeds/images', postJson)
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
		.then(cb)
)

export
const fetchEnrollAnniversary = createAction('fetch enroll anniversary', cb =>
	fetch('/users/core-profiles/enroll-anniversary', getJson)
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
    .then(res => res.data.coreUserProfileVOs)
)

// 读取消息列表
export const fetchNotificationList = createAction('fetch notification list', (arg, cb) =>
	fetch(`/messages?${util.body(arg)}`, getJson)
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
    .then(res => {
      cb && cb()
      return res.data
    })
)

export
const fetchNewStaffs = createAction('fetch new staffs', cb =>
	fetch('/users/core-profiles/new-staff', getJson)
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
    .then(res => res.data.coreUserProfileVOs)
)

export
const resetHome = createAction('reset home')

export
const feedUp = createAction('feed up', (feedId, n, cb) =>
  fetch(`/feeds/${feedId}/thumbup`, n == 1? postJson: delJson)
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
    .then(() => {
      cb && cb()
      return {
        feedId,
        n
      }
    })
)

export
const deleteComment = createAction('delete comment', (feedId, commentId, pageSize, cb) =>
  fetch(`/feeds/${feedId}/comments/${commentId}`, delJson)
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
    .then(() => {
      cb && cb()
      return {
        feedId,
        commentId,
        pageSize
      }
    })
)

export
const deleteFeed = createAction('delete feed', (feedId, cb) =>
  fetch(`/feeds/${feedId}`, delJson)
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
    .then(() => {
      cb && cb()
      return feedId
    })
)

export
const fetchSidebar = createAction('fetch sidebar', arg =>
	fetch('/sidebars/homepage', getJson)
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
    .then(data)
)
